import hashlib
import json

from flask import Flask, request
from sqlalchemy import create_engine, Integer, Column, String, Table
from sqlalchemy.orm import sessionmaker, scoped_session, declarative_base

app = Flask(__name__)

# 创建一个引擎，目的是连接到我们的数据库上
engine = create_engine('mysql+pymysql://root:123456@127.0.0.1:3306/mumushouji',echo=True)
# 打开数据库的连接会话
session = sessionmaker(engine)
# 保证线程安全
db_session = scoped_session(session)
# 获取基类
Base = declarative_base()

# sqlalchemy 是支持使用代码进行表结构创建的
# class User(Base):
#     __tablename__ = 'userssss'
#     user_id = Column(Integer, primary_key=True)
#     username = Column(String(255))
#
#
# User.metadata.create_all(engine)


class User(Base):
    # 表结构的反射加载
    __table__ = Table('user', Base.metadata, autoload_with=engine)


@app.route('/', methods=['POST'])
def login():
    # result = db_session.query(User).all()
    # for r in result:
    #     print(r.username)
    # result = db_session.query(User).first()
    # print(result.username)
    request_data = request.data
    print(request_data)
    request_data = json.loads(request_data)
    user_input_name = request_data['username']
    user_input_password = request_data['password']
    # result = db_session.query(User).filter(User.username==user_input_name).first()
    user_input_password = hashlib.md5(user_input_password.encode()).hexdigest()
    result = db_session.query(User.username, User.password).filter_by(username=user_input_name, password=user_input_password).first()
    print(result.username)
    return '登录成功'


if __name__ == '__main__':
    app.run(debug=True)
